// userPageC/pages/abulkOrderDetail/abulkOrderDetail.js
const app = getApp()
const WXAPI = require('../../../api/api')
const NEWWXAPI = require('../../../api/newApi')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1,
      // 是否显示左上角图标   1表示显示    0表示不显示
      title: '团购卡',
      // 导航栏 中间的标题
      textColor: '#fff',
      // 标题颜色
      bgColor: '#F75D0B',
      // 导航栏背景颜色
      isloading: false
    },
    typeList:[
      {id: 0,value: '套餐详情',hash: 'package'},
      {id: 1,value: '购买须知',hash: 'buy'},
      {id: 2,value: '图文详情',hash: 'graphic'},
    ],
    current: 0,
    winHeight: '100%',
    toView: 'productBox',//锚点跳转的ID
    actionView: 'productBox',//控制导航显示
    packageTop: 0,//商品模块距离顶部的距离
    buyTop: 0,//评价模块距离顶部的距离
    graphicTop: 0,//详情模块距离顶部的
    scrollY: false,
    vouchersShow: false,
    customerCardId: '',
    lat: app.globalData.lat,
    lnt: app.globalData.lnt,
    orderData: {},
    productDetail: [],//套餐详情
    imgHttp: app.globalData.imgHttp,
    countdown: '',
    second: '',
    timer: null,
    phoneShow: false,
    payData: {},//拉起订单的参数
    returnShow: false,
    sumitReturnLoad: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    var customerCardId = options.customerCardId
    // var customerCardId = "1515877310420205570"
    this.getphone()
    this.setData({
      statusHeight: app.gettop.height,
      status: app.gettop.status,
      navHeight: app.gettop.navHeight,
      mobbleBottom: app.mobile.mobbleBottom,
      customerCardId: customerCardId
    });
    await this.getDetail()
    await this.getTop()
  },
  //获取详情
  getDetail(){
    console.log('this.data.lnt',this.data.lnt)
    return new Promise((resolve,reject) => {
      var data = {
        customerCardId: this.data.customerCardId,
        lnt: this.data.lnt,
        lat:  this.data.lat,
      }
      WXAPI.abulkOrderDetail(data,res => {
        const data = res.result
        if(res.code == 200){
          var productDetail = []
          if(data.productDetail){
             productDetail = JSON.parse(data.productDetail)
          }
          this.setData({
            orderData: data,
            productDetail: productDetail,
            second: data.surplusTime,
            phoneList: data.phone.split(',')
          })
          console.log('phoneList',this.data.phoneList)
          if (data.status == 1) {
            this.countTime();
          }
          resolve()
          
          console.log('productDetail',this.data.productDetail)
          
        }
      })
    })
    
    
  },
  countTime() {
    var that = this;
    var leftTime = this.data.second; //时间差     
    var newSecond = leftTime--;
    var m, s;
    if (leftTime >= 0) {
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
      s = s < 10 ? "0" + s : s;
      m = m < 10 ? "0" + m : m;
      that.setData({
        second: leftTime,
        countdown: m + ':' + s 
      }); //递归每秒调用countTime方法，显示动态时间效果

      console.log(that.data.countdown);
      this.setData({
        timer: setTimeout(that.countTime, 1000)
      })
    } else {
      clearTimeout(this.data.timer)
      console.log('已截止');
    }
  },
  //打开电话弹窗
  handlePhoneShow() {
    this.setData({
      phoneShow: !this.data.phoneShow
    });
  },
  //导航到地方
  getLocation: function () {
    const that = this;
    wx.getSetting({
      success: res => {
        var statu = res.authSetting;

        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
          wx.showModal({
            title: '',
            content: '需要获取你的地理位置才能进行导航，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none'
                });
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    // console.log('dataAu:success', dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      //再次授权，调用wx.getLocation的API
                      that.newgetLocation(dataAu, callback);
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none'
                      });
                    }
                  }
                });
              }
            }
          });
        } else {
          that.newgetLocation();
        }
      }
    });
  },
  newgetLocation() {
    const storesData = this.data.orderData;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.openLocation({
          //​使用微信内置地图查看位置。
          latitude: storesData.shopLat,
          //要去的纬度-地址
          longitude: storesData.shopLnt,
          //要去的经度-地址
          name: storesData.merchantName,
          address: storesData.locateAddress
        });
      }
    });
  },
  //拨打电话
  freeTell(e) {
    var phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    });
  },
  //获取屏幕各项数据
  getphone(){
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        var num = app.gettop.height
        if(that.data.scrollY){
          //屏幕的宽度/屏幕的高度 = 微信固定宽度(750)/微信高度
          that.setData({
            winHeight: res.screenHeight-num-39-74+'px'  
          }) 
        }else{
          that.setData({
            winHeight: res.screenHeight+'px'  
          }) 
        }
        
      }
    });
  }, 
  getTop(){
    // 获取各模块距离顶部的距离
    new Promise(resolve => {
      let query = wx.createSelectorQuery();
      query.select('#package').boundingClientRect();
      query.select('#buy').boundingClientRect();
      query.select('#graphic').boundingClientRect();
      query.exec(function (res) {
        resolve(res);
      });
    }).then(res => {
      this.setData({
        packageTop: res[0].top,
        buyTop: res[1].top,
        graphicTop: res[2].top
      });
      console.log('packageTop',this.data.packageTop)
      console.log('buyTop',this.data.buyTop)
      console.log('graphicTop',this.data.graphicTop) //
    });
  },
  scrollTo(e){
    let scrollTop = e.detail.scrollTop;  //滚动的Y轴
    
    if(scrollTop >= this.data.packageTop){   
      this.setData({
        scrollY: true
      })
    }else{
      this.setData({
        scrollY: false
      })
    }
    // console.log('scrollTop',scrollTop)
    this.getphone()
    if(scrollTop >= this.data.packageTop && scrollTop < this.data.buyTop){
      this.setData({
        current: 0 ,

      })
    }else if(scrollTop >= this.data.buyTop && scrollTop < this.data.graphicTop){
      this.setData({
        current: 1     
      })
    }else if(scrollTop >= this.data.graphicTop){
      this.setData({
        current: 2    
      })
    }
    console.log('current',this.data.current)
    //this.$apply();//WEPY更新数据
  },
  
  //切换选项
  toViewClick(e){
    const id = e.currentTarget.dataset.id;
    console.log('e',e)
    this.setData({
      current: id,
      toView: e.currentTarget.dataset.hash,  
      actionView: e.currentTarget.dataset.hash
    })
    console.log('toView',this.data.toView)
  },
  //关闭弹窗
  handleChoose(){
    this.setData({
      vouchersShow: false,
    })
  },
  //打开弹窗
  handleShow(){
    this.setData({
      vouchersShow: true,
    })
  },
  //取消订单
  handleCancel(){
    var that = this
    wx.showModal({
      content: "确认取消该订单？",
      cancelColor: '#999999',
      confirmColor: '#FF5800',
      success(res) {
        if (res.confirm) {
          var url = `/app/v1/groupon/order/cancel/${that.data.customerCardId}`
          WXAPI.cancelOrder(url,'',res => {
            const data = res.result
            if(res.code == 200){
              wx.showToast({
                title: '取消成功',
              });
              setTimeout(() => {
                wx.redirectTo({
                  url: '/userPageB/pages/order/order',
                })
              }, 2000);
            }
          })
        } else if (res.cancel) {
         
        } else {
          // what happend?
        }
      },
     
    });
  },
  //伤删除订单
  handleDelete(){
    var that = this
    wx.showModal({
      content: "确认删除该订单？",
      cancelColor: '#999999',
      confirmColor: '#FF5800',
      success(res) {
        if (res.confirm) {
          var url = `/app/v1/groupon/order/${that.data.customerCardId}`
          WXAPI.deleteOrder(url,'',res => {
            const data = res.result
            if(res.code == 200){
              wx.showToast({
                title: '删除成功',
              });
              setTimeout(() => {
                wx.redirectTo({
                  url: '/userPageB/pages/order/order',
                })
              }, 2000);
            }
          })
        } else if (res.cancel) {
         
        } else {
          // what happend?
        }
      },
     
    });
  },
  //申请退款
  handleRefund(e){
    const id = e.currentTarget.dataset.id
    console.log('id',id)
    wx.navigateTo({
      url: '/userPageC/pages/refund/refund?customerCardId='+id,
    });
  },
  //待支付订单去支付
  handlepay(e){
    var customerCardId = e.currentTarget.dataset.id
    var url = `/app/v1/groupon/order/toPay/${customerCardId}`
    WXAPI.getToPay(url,'',res => {
      const data = res.result
      if(res.code == 200){
        const payData = JSON.parse(data)
        console.log('payData',payData)
        this.setData({
          payData: payData
        })
        this.pay()
      }
    })
  },
  pay(){
    const that = this
    wx.pay({
      orderInfo: {
        order_id: that.data.payData.order_id,
        order_token: that.data.payData.order_token,
      },
      service: 5,
      success(res) {
        console.log('拉起支付',res)
        if (res.code == 0) {
          // 支付成功处理逻辑，只有res.code=0时，才表示支付成功
          // 但是最终状态要以商户后端结果为准
          wx.showToast({
            title: '支付成功',
          });
          setTimeout(() => {
            wx.navigateTo({
              url: '/userPageB/pages/order/order',
            });
          }, 2000);
          
        }
      },
      fail(res) {
        // 调起收银台失败处理逻辑
      },
    });
  },
  closeReturn() {
    this.setData({
      returnShow: false
    })
  },
  returnCard() { //体验卡退卡
    this.setData({
      returnShow: true
    })
  },
  sumitReturn(e) { //确认退卡（体验卡）
    console.log('哈哈哈')
    this.setData({
      sumitReturnLoad: true,
    })
    var that = this
    let cardId = e.currentTarget.dataset.info.customerCardId
    var data = {
      cardId: cardId
    }
    NEWWXAPI.experienceReturnCard(data, (res) => {
      if (res.code === 200) {
        wx.showToast({
          title: '确认退卡成功',
          icon: 'none'
        })
           
        setTimeout(() => {
          that.setData({
            returnShow: false
          })
          wx.switchTab({
            // url: '/pages/abulkPage/abulkPage',
            url: '/pages/userPersonal/userPersonal',
          })
        }, 600)
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none'
        })
      }
    })
  },
  //回到首页
  goIndex(){
    wx.switchTab({
      // url: '/pages/assets/assets',
      url:'/pages/userMarket/userMarket'
    });
  },
  //返回上一级
  back(){
    wx.navigateBack({
      delta: 1
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearTimeout(this.data.timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.setData({
      second: 0
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})